// 阿里云接口处理云对象
module.exports = {
	_before: function () { // 通用预处理器

	},
	
	/**
	 * 获取语音合成task_id
	 * @param {object} data 要合成的参数
	 * @returns {object} 返回结果
	 */
	
	async getAudioTaskId(data) {
		// 参数校验，如无参数则不需要
		if (!data) {
			return {
				errCode: 'PARAM_IS_NULL',
				errMsg: 'data参数不能为空'
			}
		}
		
		var url = 'https://nls-gateway-cn-shanghai.aliyuncs.com/rest/v1/tts/async';
		const res = await uniCloud.httpclient.request(url, {
		    method: 'POST',
			timeout:600000,
			data:data,
			headers: {
			    'Content-Type': 'application/json'
			},
		    contentType: 'json', 
		    dataType: 'json'
		  })
		
		return {
			code:200,
			message:'请求成功',
			result:res.data
		}
	},
	
	/**
	 * 作用：获取语音合成的最终结果
	 */
	
	/**
	 * 获取语音合成最终结果
	 * @param {object} data 要合成的参数
	 * @returns {object} 返回结果
	 */
	
	async getAudioTaskResult(data) {
		// 参数校验，如无参数则不需要
		if (!data) {
			return {
				errCode: 'PARAM_IS_NULL',
				errMsg: 'data参数不能为空'
			}
		}
		
		var url = 'https://nls-gateway-cn-shanghai.aliyuncs.com/rest/v1/tts/async?appkey='+data.appkey+'&task_id='+data.task_id+'&token='+data.token;
		const res = await uniCloud.httpclient.request(url, {
			timeout:600000,
			headers: {
			    'Content-Type': 'application/json'
			},
			contentType: 'json', 
			dataType: 'json'
		  })
		
		return {
			code:200,
			message:'请求成功',
			result:res.data
		}
	},
	
	
	/**
	 * 作用：让音色的使用人数加1
	 * @param {string} keyword 音色数据库中的唯一关键词
	 * @param {string} musicId 背景音乐id
	 */
	async setTimbreAndbjMusicUseNumber(keyword,musicId = null){
		var db = uniCloud.database();
		var timbreResult = await db.collection('timbre').where({voice:keyword}).update({
			use_number:db.command.inc(1)
		});
		if(musicId != null){
			var musicResult = await db.collection('music').where({_id:musicId}).update({
				use_number:db.command.inc(1)
			});
		}else{
			var musicResult = '';
		}
		
		
		return {
			code:200,
			message:'更新成功',
			result:{
				timbreResult:timbreResult,
				musicResult:musicResult
			}
		}
	},
	
	/**
	 * 作用:插入创作记录表
	 * 
	 */
	async addCreateHistory(data,content,userinfo){
		var db = uniCloud.database();
		var addData = {
			create_uid:userinfo._id,//创建人uid
			application:{
				id:data._id,
				title:'文案配音'
			},
			works:{
				title:'文案配音',
				content:content,
				audio_url:data.data.audio_address,
				create_date:new Date().getTime()
			},
			duration:data.duration
		}
		
		var result = await db.collection('create_history').add(addData);
		return {
			code:200,
			message:'添加成功',
			result:result
		}
	},
	
	/**
	 * 作用：文案配音语音合成后存入digital_history表
	 * @param audio:要存入的音频数据
	 * @param userinfo:登录的用户信息
	 */
	async addDigitalHistory(audio,userinfo){
		var db = uniCloud.database();
		var addData = {
			uid:userinfo._id,
			audio_src:audio.data.audio_address,
			title:'我的配音',
			type:'audio-hecheng',
			duration:audio.duration,
			create_date:new Date().getTime()
		}
		
		var result = await db.collection('digital_history').add(addData);
		return {
			code:200,
			message:'添加成功',
			result:result
		}
	},
	
	/**
	 * 作用：查询出配音人
	 * 
	 */
	async getTimbre(){
		const redis = uniCloud.redis();
		var redisData = await redis.get('timbre-data');
		if(!redisData){
			var db = uniCloud.database();
			var result = await db.collection('timbre').orderBy('use_number','desc').where({type:'aliyun'}).limit(500).get();
			var data = result.data;
			await redis.set('timbre-data',JSON.stringify(result.data),'EX',86400);
		}else{
			var data = JSON.parse(redisData);
		}
		
		return {
			code:200,
			message:'请求成功',
			result:data
		}
	},
	
	/**
	 * 作用：获取背景音乐列表
	 * @param {string} id 背景音乐分类id
	 * @return {object}
	 */
	async getMusicResult(id){
		const redis = uniCloud.redis();
		redis.del('music'+id);
		var redisData = await redis.get('music'+id);
		if(!redisData){
			var db = uniCloud.database();
			var result = await db.collection('music').orderBy('use_number','desc').where({type:id}).limit(500).get();
			var data = result.data;
			if(data && data[0]){
				await redis.set('music'+id,JSON.stringify(result.data),'EX',86400);
			}
			
		}else{
			var data = JSON.parse(redisData);
		}
		
		return {
			code:200,
			message:'请求成功',
			result:data
		}
	},
	
	/**
	 * 作用：获取应用详情
	 * @param {string} id 应用的id
	 * @return {object}
	 */
	async getApplicationDetail(id){
		const redis = uniCloud.redis();
		var redisData = await redis.get('application-detail'+id);
		if(!redisData){
			var db = uniCloud.database();
			var result = await db.collection('applications').orderBy('use_number','desc').where({_id:id}).get();
			var data = result.data[0];
			await redis.set('application-detail'+id,JSON.stringify(result.data[0]),'EX',30);
		}else{
			var data = JSON.parse(redisData);
		}
		
		return {
			code:200,
			message:'请求成功',
			result:data
		}
	},
	
	
	
	/**
	 * 复刻音色
	 * @param {object} data 要合成的参数
	 * @returns {object} 返回结果
	 */
	
	async setCosyVoice(data) {
		// 参数校验，如无参数则不需要 
		if (!data) {
			return {
				errCode: 'PARAM_IS_NULL',
				errMsg: 'data参数不能为空'
			}
		}
		
		var url = 'https://dashscope.aliyuncs.com/api/v1/services/audio/tts/customization';
		const res = await uniCloud.httpclient.request(url, {
			timeout:120000,
			data:data,
			headers: {
				'Authorization':'Bearer sk-986abea2283641f9b6f0573f71ff0f44',
				'Content-type':'application/json'
			},
			method:"POST",
			contentType: 'json', 
			dataType: 'json'
		  })
		
		return {
			code:200,
			message:'请求成功',
			result:res.data
		}
	},
	
	
	/**
	 * 删除复刻的音色
	 * @param {object} data 要删除的音色参数
	 * @returns {object} 返回结果
	 */
	
	async delCosyVoice(data) {
		// 参数校验，如无参数则不需要 
		if (!data) {
			return {
				errCode: 'PARAM_IS_NULL',
				errMsg: 'data参数不能为空'
			}
		}
		
		var url = 'https://dashscope.aliyuncs.com/api/v1/services/audio/tts/customization';
		const res = await uniCloud.httpclient.request(url, {
			timeout:120000,
			data:data,
			headers: {
				'Authorization':'Bearer sk-986abea2283641f9b6f0573f71ff0f44',
				'Content-type':'application/json'
			},
			method:"POST",
			contentType: 'json', 
			dataType: 'json'
		  })
		
		return {
			code:200,
			message:'请求成功',
			result:res.data
		}
	},
	
	
	/**
	 * 作用：获取实时音频流合成结果
	 */
	async getSendSynthesis(data){
		var url = 'http://ai.yipaidaojia.com/api/get_cosyVoice_audio';
		const res = await uniCloud.httpclient.request(url, {
			timeout:300000,
			data:data,
			method:"POST",
			dataType: 'json',
			contentType:'json'
		  })
		
		return {
			code:200,
			message:'请求成功',
			result:res.data
		}
	},
	/**
	 * @作用:删除线上音频文件
	 */
	async removeSynthesis(filePath){
		var url = 'http://ai.yipaidaojia.com/api/del_cosyVoice_audio';
		const res = await uniCloud.httpclient.request(url, {
			timeout:300000,
			data:filePath,
			method:"POST",
			dataType: 'json',
			contentType:'json'
		  })
		
		return {
			code:200,
			message:'删除成功',
			result:res.data
		}
	},
	
	//获取视频结果taskid
	async getVideoTask(data){
		// 参数校验，如无参数则不需要
		if (!data) {
			return {
				errCode: 'PARAM_IS_NULL',
				errMsg: 'data参数不能为空'
			}
		}
		
		var url = 'https://dashscope.aliyuncs.com/api/v1/services/aigc/image2video/video-synthesis/';
		const res = await uniCloud.httpclient.request(url, {
			timeout:120000,
			data:data,
			headers: {
				'Authorization':'Bearer sk-986abea2283641f9b6f0573f71ff0f44',
				'Content-type':'application/json',
				'X-DashScope-Async':'enable'
			},
			method:"POST",
			contentType: 'json', 
			dataType: 'json'
		  })
		
		return {
			code:200,
			message:'请求成功',
			result:res.data
		}
	},
	
	/**
	 * 作用：获取视频查询结果
	 * @param {Object} task_id
	 */
	async getVideoTaskResult(task_id){
		
		// 参数校验，如无参数则不需要
		if (!task_id) {
			return {
				errCode: 'PARAM_IS_NULL',
				errMsg: 'data参数不能为空'
			}
		}
		
		var url = 'https://dashscope.aliyuncs.com/api/v1/tasks/'+task_id;
		const res = await uniCloud.httpclient.request(url, {
			timeout:120000,
			headers: {
				'Authorization':'Bearer sk-986abea2283641f9b6f0573f71ff0f44'
			},
			method:"GET",
			contentType: 'json', 
			dataType: 'json'
		  })
		
		return {
			code:200,
			message:'请求成功',
			result:res.data
		}
		
		
	},
	
	/**
	 * 作用：获取文生视频task_id
	 * 
	 */
	async getVideoTaskId(data,id){
		// 参数校验，如无参数则不需要
		if (!data || !id) {
			return {
				errCode: 'PARAM_IS_NULL',
				errMsg: 'data参数不能为空'
			}
		}
		//更新使用次数
		var db = uniCloud.database();
		await db.collection('application_class').update({
			use_number:db.command.inc(1)
		});
		
		var url = 'https://dashscope.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis';
		const res = await uniCloud.httpclient.request(url, {
			timeout:120000,
			data:data,
			headers: {
				'Authorization':'Bearer sk-986abea2283641f9b6f0573f71ff0f44',
				'Content-Type':'application/json',
				'X-DashScope-Async':'enable'
			},
			method:"POST",
			contentType: 'json', 
			dataType: 'json'
		  })
		
		return {
			code:200,
			message:'请求成功',
			result:res.data
		}
	},
	
	/**
	 * 作用：获取文生视频最终结果
	 * 
	 */
	async getWenshengVideoTaskResult(taskId){
		// 参数校验，如无参数则不需要
		if (!taskId) {
			return {
				errCode: 'PARAM_IS_NULL',
				errMsg: 'taskId参数不能为空'
			}
		}
		
		var url = 'https://dashscope.aliyuncs.com/api/v1/tasks/'+taskId;
		const res = await uniCloud.httpclient.request(url, {
			timeout:120000,
			headers: {
				'Authorization':'Bearer sk-986abea2283641f9b6f0573f71ff0f44',
			},
			method:"GET",
			contentType: 'json',
			dataType: 'json'
		  })
		
		return {
			code:200,
			message:'请求成功',
			result:res
		}
	},
	
	/**
	 * 作用：根据视频链接获取优化过后的视频和webp动画图片
	 * 
	 */
	async getVideoResult(videoUrl,taskId,size,id){
		// 参数校验，如无参数则不需要
		if (!videoUrl || !taskId || !size || !id) {
			return {
				errCode: 'PARAM_IS_NULL',
				errMsg: 'videoUrl和taskId、size、id参数不能为空'
			}
		}
		var data = {
			video_url:videoUrl,
			task_id:taskId,
			size:size
		}
		var url = 'http://ai.mofang360.com/getVideoResult.php';
		const res = await uniCloud.httpclient.request(url, {
			timeout:120000,
			method:"POST",
			data:data,
			contentType: 'json',
			dataType: 'json' 
		  })
		var result = res.data;
		var resData = res.data.result;
		if(result.code==200){
			var updateData = {
				video_url:resData.video_url,
				video_small_url:resData.video_small_url,
				webp_url:resData.webp_url,
				webp_static_url:resData.webp_static_url,
				color:resData.color
			}
			var db = uniCloud.database();
			var updateResult = await db.collection('create_result').where({_id:id}).update(updateData);
			
			return {
				code:200,
				message:'请求成功',
				result:updateData
			}
		}else{
			return {
				code:101,
				message:'结果已返回但更新到数据库失败',
				result:res.data
			}
		}
		
	},
	
	/**
	 * 作用：利用php在后台通过websocket获取语音合成结果
	 */
	
	async getCosyVoiceFromPhp(data){
		var url = 'http://ai.mofang360.com/cosyVoice.php';
		const res = await uniCloud.httpclient.request(url, {
			timeout:3000000,
			method:"POST",
			data:data,
			contentType: 'json',
			dataType: 'json' 
		  })
		  
		  return {
			  code:200,
			  message:'请求成功',
			  result:res
		  }
	},
	
	/**
	 * 作用：根据视频地址获取视频第一针作为视频封面
	 * @param {string} videoUrl 视频地址
	 * @param {id} 记录id，用作更新到数据库
	 * @param {fileName} uuid文件名
	 * @return 返回获取后更新到数据库的结果
	 */
	async getPosterFromVideo(videoUrl,id,fileName){
		var url = 'http://ai.mofang360.com/getPosterFromVideo.php';
		var data = {
			token:'sk-986abea2283641f9b6f0573f71ff0f44',
			videoUrl:videoUrl,
			fileName:fileName
		}
		const res = await uniCloud.httpclient.request(url, {
			timeout:3000000,
			method:"POST",
			data:data,
			contentType: 'json',
			dataType: 'json' 
		  })
		  
		  var posterUrl = res.data.result;
		  //更新到数据库
		  if(posterUrl && id){
			  var db = uniCloud.database();
			  const result = await db.collection('material').where({_id:id}).update({poster:posterUrl});
			  
			  return {
			  	code:200,
			  	message:'请求成功',
			  	result:res
			  }
		  }else{
			  return {
			  	code:'error',
			  	message:'获取视频封面错误',
			  	result:res
			  }
		  }
		 
	}
	
}
